package 练习11_线程池综合使用案例;

import java.util.concurrent.*;

/**
 * @ClassName: ThreadPoolStudy01
 * @Author: AllenSun
 * @Date: 2025/10/23 23:17
 */
public class ThreadPoolStudy00_unsafe {

    public static void main(String[] args) {
        UserAccount zhangsan = new UserAccount("张三",100);
        UserAccount lisi = new UserAccount("李四",0);

        // ExecutorService executorService = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor executorService =
                new ThreadPoolExecutor(
                        5, 10, 30, TimeUnit.SECONDS,
                        new ArrayBlockingQueue<>(90),
                        new ThreadPoolMonitorHelper.NamedThreadFactory("app-worker"),
                        // ThreadPoolMonitorHelper.RejectedCounter.createHandler()
                        new ThreadPoolExecutor.CallerRunsPolicy()
                );
        double amount = 1;
        int taskCount = 100;
        CountDownLatch countDownLatch = new CountDownLatch(taskCount);
        // 启动监控任务（每5秒监控一次）
        ScheduledExecutorService monitorExecutor =
                Executors.newSingleThreadScheduledExecutor();
        monitorExecutor.scheduleAtFixedRate(() -> {
            try {
                ThreadPoolMonitorHelper.monitor(executorService, "Worker线程池");
                ThreadPoolMonitorHelper.monitorThreads("main");
            } catch (Exception e) {
                e.printStackTrace();
            }

        }, 0, 5, TimeUnit.SECONDS);

        for (int i = 0; i < taskCount; i++) {

            executorService.execute(()->{
                try {
                    transfer01(zhangsan,lisi,amount);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    throw new RuntimeException(e);
                } finally {
                    countDownLatch.countDown();
                }
            });

        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        ThreadPoolShutdownHelper.gracefulShutdown(executorService);
        ThreadPoolShutdownHelper.gracefulShutdown(monitorExecutor);

    }

    public static void transfer01(UserAccount from,UserAccount to,double amount) throws InterruptedException {
        double fromBalance = from.getBalance();
        double toBalance = to.getBalance();
        if (fromBalance >= amount) {
            from.setBalance(fromBalance - amount);
            Thread.sleep(1000);
            to.setBalance(toBalance + amount);
            System.out.println("当前线程："+Thread.currentThread().getName()+"；转出账户：" + from.getUserName() + "，余额：" + from.getBalance()+
                    "；转入账户：" + to.getUserName() + "，余额：" + to.getBalance());
        } else {
            System.out.println("当前线程："+Thread.currentThread().getName()+"；余额不足");
        }
    }
}
